//
//  SNSelectDatePickerView.m
//  SNWF
//
//  Created by MJ on 15/4/27.
//  Copyright (c) 2015年 TJ. All rights reserved.
//

#import "SNSelectDatePickerView.h"
#import "ImageUtil.h"
#import "Header.h"
#define kDatePickerHeight   300.f
#define kDateViewHeight     300.f
@interface SNSelectDatePickerView ()
{
    UIDatePicker *_datePicker;      //日期选择器
    UIButton     *_btnLeftCancel;   //左边取消按钮
    UIButton     *_btnRightConform; //右边确定按钮
    BOOL         _isSelectDate;     //是否选择日期
    UIToolbar    *containToolBar;
    NSString *_ID; //判断选择哪个日历格式
    UIView *whiteView;
}
@end

@implementation SNSelectDatePickerView

+ (SNSelectDatePickerView *)shareInstance
{
    static SNSelectDatePickerView *dateInstance ;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        dateInstance = [[SNSelectDatePickerView alloc] init];
    });
    return dateInstance;
}
//- (instancetype)init:(NSString *)ID
- (instancetype)init:(NSString *)ID
{
    if (self = [super init])
    {
        //        CGRect frect = CGRectZero;
        //        frect.size.height = kDateViewHeight;
        //        frect.origin.y   = SCREEN_HEIGHT;
        //        frect.size.width = SCREEN_WIDTH;
        //        self.frame = frect;
        self.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        self.backgroundColor = [UIColor clearColor];
        _ID = ID;
        [self setUp];
        
    }
    return self;
}
/**
 *  创建按钮和日期选择器
 */
- (void)setUp
{
    UIButton *button  = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(0 , 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    [button addTarget:self action:@selector(yichu) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:button];
    button.backgroundColor = [UIColor blackColor];
    button.alpha = 0.5;
    
    /**toolbar工具条*/
    containToolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT-kDateViewHeight-35, SCREEN_WIDTH, 35)];
    //    containToolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 115, SCREEN_WIDTH, 35)];
    
    containToolBar.backgroundColor = [ImageUtil colorWithRgb:0x000000];
    [self addSubview:containToolBar];
    /**取消按钮*/
    _btnLeftCancel = [UIButton buttonWithType:UIButtonTypeCustom];
    _btnLeftCancel.frame = CGRectMake(0, 0, 60, 35);
    _btnLeftCancel.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    _btnLeftCancel.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    [_btnLeftCancel setTitle:@"取消" forState:UIControlStateNormal];
    [_btnLeftCancel setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [_btnLeftCancel addTarget:self action:@selector(cancelDatePicker:) forControlEvents:UIControlEventTouchUpInside];
    [containToolBar addSubview:_btnLeftCancel];
    
    
    
    /**确定按钮*/
    _btnRightConform = [UIButton buttonWithType:UIButtonTypeCustom];
    _btnRightConform.frame = CGRectMake(SCREEN_WIDTH-60, 0, 60, 35);
    [_btnRightConform setTitle:@"确定" forState:UIControlStateNormal];
    _btnRightConform.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    _btnRightConform.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 10);
    [_btnRightConform addTarget:self action:@selector(ConformDatePicker:) forControlEvents:UIControlEventTouchUpInside];
    [containToolBar addSubview:_btnRightConform];
    [_btnRightConform setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    
    /**datepicker*/
    _datePicker = [[UIDatePicker alloc]init];
    _datePicker.backgroundColor = [UIColor whiteColor];
    //    _datePicker.frame = CGRectMake(0, SCREEN_HEIGHT+35, SCREEN_WIDTH, kDateViewHeight);
    _datePicker.frame = CGRectMake(0, SCREEN_HEIGHT-kDateViewHeight, SCREEN_WIDTH, kDateViewHeight);
    //    _datePicker.frame = CGRectMake(0, 150, SCREEN_WIDTH, kDateViewHeight);
    //    *设置格式显示年月日
    if ([_ID intValue] == 1) {
        
        
        _datePicker.datePickerMode = UIDatePickerModeDateAndTime;
        _datePicker.locale = [NSLocale localeWithLocaleIdentifier:@"zh-CN"];
        [_datePicker addTarget:self action:@selector(pickerviewChanged:) forControlEvents:UIControlEventValueChanged];
        NSDate *date = [_datePicker date];
        _datePicker.minimumDate = date;
        [self addSubview:_datePicker];
        
        whiteView = [UIView new];
        whiteView.frame = CGRectMake(0, kMaxY(containToolBar.frame),(WindowWidth-13)/2 , 130);
        whiteView.backgroundColor = [UIColor whiteColor];
        //        [self addSubview:whiteView];
    }
    if ([_ID intValue] == 2) {
        _datePicker.datePickerMode = UIDatePickerModeDate;
        [self addSubview:_datePicker];
        
        whiteView = [UIView new];
        whiteView.frame = CGRectMake(0, kMaxY(containToolBar.frame),(WindowWidth-13)/2 , 130);
        whiteView.backgroundColor = [UIColor blackColor];
        //        [self addSubview:whiteView];
    }
    /**本地化为中文公历*/
    _datePicker.locale = [NSLocale localeWithLocaleIdentifier:@"zh-CN"];
    [_datePicker addTarget:self action:@selector(pickerviewChanged:) forControlEvents:UIControlEventValueChanged];
    
    
    
}
/**
 *   取消按钮添加事件
 *
 *  @param sender
 */
- (void)cancelDatePicker:(UIButton *)sender
{
    //    [self dismissDatePiker];
    //    selectDateCompleteHander(@"");
    [self removeFromSuperview];
}
/**
 *  确定按钮添加事件
 *
 *  @param sender
 */
- (void)ConformDatePicker:(UIButton *)sender
{
    if (sender.isTouchInside)
    {
        [self removeFromSuperview];
        /**
         *  如果没有选择日期，则当天日期作为参数传递
         */
        if (!_isSelectDate)
        {
            if (selectDateCompleteHander)
            {
                
                //selectDateCompleteHander([self dealselectDate:[NSDate date]]);
                NSDate *selected = [NSDate date];
                
                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                if ([_ID intValue] == 1) {
                    [dateFormatter setDateFormat:@"MM-dd HH:mm"];
                }
                if ([_ID intValue] == 2) {
                    [dateFormatter setDateFormat:@"YYYY-MM-dd"];
                }
                NSString *currentOlderOneDateStr = [dateFormatter stringFromDate:selected];
                selectDateCompleteHander(currentOlderOneDateStr);
            }
            
        }
        _isSelectDate = NO;
        
    }
    
}
/**
 *  获取当前选择的日期
 *
 *  @param picker
 */
- (void)pickerviewChanged:(UIDatePicker *)picker
{
    _isSelectDate = YES;
    
    if (selectDateCompleteHander)
    {
        if ([_ID  isEqual: @"1"]) {
            NSDate *selected = [picker date];
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"MM-dd HH:mm"];
            NSString *currentOlderOneDateStr = [dateFormatter stringFromDate:selected];
            selectDateCompleteHander(currentOlderOneDateStr);
        }
        if ([_ID  isEqual: @"2"]) {
            NSDate *selected = [picker date];
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"YYYY-MM-dd "];
            NSString *currentOlderOneDateStr = [dateFormatter stringFromDate:selected];
            selectDateCompleteHander(currentOlderOneDateStr);
        }
        
        
        //        selectDateCompleteHander([self dealselectDate:picker.date]);
        
    }
}
/**
 *  格式化处理获取的日期
 *
 *  @param date 当前日期或者是选择的日期
 *
 *  @return 返回一个已经格式化日期字符串
 */
//- (NSString*)dealselectDate:(NSDate *)date
//{
////    NSArray * arrOfWeek=@[@"周日",@"周一",@"周二",@"周三",@"周四",@"周五",@"周六"];
//    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian] ;
//    NSDateComponents *comps = [[NSDateComponents alloc] init] ;
////    NSInteger unitFlags = NSCalendarUnitYear |NSCalendarUnitMonth |NSCalendarUnitDay |NSCalendarUnitWeekday |NSCalendarUnitHour |
//    NSInteger unitFlags = NSCalendarUnitYear |NSCalendarUnitMonth |NSCalendarUnitDay ;
//
//    comps = [calendar components:unitFlags fromDate:date];
//    NSInteger week = [comps weekday];
//    NSInteger year=[comps year];
//    NSInteger month = [comps month];
//    NSInteger day = [comps day];
//    NSInteger xiaoshi = [comps hour];
//    NSInteger fen = [comps minute];
//    /**对月份进行处理月份的位数一位数时需要在月份前面添加“0”*/
//    NSString *monthFormatter = [NSString stringWithFormat:@"%ld",month];
//    if (monthFormatter.length == 1) {
//        monthFormatter = [NSString stringWithFormat:@"0%@",monthFormatter];
//    }
//    else
//    {
//        monthFormatter = monthFormatter;
//    }
//    /**特殊时间格式4/27(周一)*/
////    NSString *formatterDate = [NSString stringWithFormat:@"%@/%ld(%@)",monthFormatter,day,[arrOfWeek objectAtIndex:week-1]];
//    NSString *appendDate = [NSString stringWithFormat:@"%@-%ld %ld:%ld ",monthFormatter,day, xiaoshi,fen];
//    return appendDate;
//}
/**
 *  显示日期选择器
 *
 *  @param baseView            显示在父视图
 *  @param dateCompleteHandler 把获取的日期作为参数传递
 */
- (void)showInView:(UIView *)baseView andSelectDateCompleteHander:(SelectDatePickerCompleteHandler)dateCompleteHandler
{
    
    selectDateCompleteHander = dateCompleteHandler;
    [baseView addSubview:self];
    
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        
        CGRect selfRect = self.frame;
        selfRect.origin.y = SCREEN_HEIGHT-kDateViewHeight;
        //        self.frame = selfRect;
        //
        CGRect dateRect = _datePicker.frame;
        dateRect.size.height = kDatePickerHeight;
        _datePicker.frame = dateRect;
        //        _datePicker.frame = CGRectMake(0, SCREEN_HEIGHT-kDateViewHeight-100, SCREEN_WIDTH, kDateViewHeight);
        //        _datePicker.frame = CGRectMake(0, 150, SCREEN_WIDTH, kDateViewHeight);
        
        //        containToolBar.frame = CGRectMake(0, SCREEN_HEIGHT-kDateViewHeight-135, SCREEN_WIDTH, 35);
        containToolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 115, SCREEN_WIDTH, 35)];
        
        
    } completion:^(BOOL finished) {
        
    }];
    
}
/**
 *  显示日期选择器
 *
 *  @param baseView             显示在父视图
 *  @param dateCompleteHandler 把获取的日期作为参数传递
 */
+ (void)showInView:(UIView *)baseView andSelectDateCompleteHander:(SelectDatePickerCompleteHandler)dateCompleteHandler
{
    [[SNSelectDatePickerView shareInstance] showInView:baseView andSelectDateCompleteHander:dateCompleteHandler];
}


/**
 *  移除日期选择器
 */
- (void)dismissDatePiker
{
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        /**
         *  重新设置self(view)的y坐标
         */
        //        CGRect selfRect = self.frame;
        //        selfRect.origin.y = SCREEN_HEIGHT;
        ////        self.frame = selfRect;
        //
        //        /**
        //         *  重新设置日期选择器的高度
        //         */
        //        CGRect dateRect = _datePicker.frame;
        //        dateRect.size.height =0;
        //        _datePicker.frame = dateRect;
        _datePicker.frame = CGRectMake(0, SCREEN_HEIGHT+35, SCREEN_WIDTH, kDateViewHeight);
        containToolBar.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 35);
        //        containToolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 115, SCREEN_WIDTH, 35)];
    } completion:^(BOOL finished) {
        
        [self removeFromSuperview];
        
    }];
    
}
-(void)yichu{
    //    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
    //        _datePicker.frame = CGRectMake(0, SCREEN_HEIGHT+35, SCREEN_WIDTH, kDateViewHeight);
    ////        containToolBar.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 35);
    //        containToolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 115, SCREEN_WIDTH, 35)];
    //    } completion:^(BOOL finished) {
    //        
    [self removeFromSuperview];
    
    //    }];
}
@end
